package com.gxc.controller;

import com.gxc.dao.jpa.UserRepository;
import com.gxc.entity.User;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 测试 list 遍历.
 *
 * @author 宫新程
 * @since 2018/12/3 3:24 PM
 */
@Controller
public class UserController {

  @Resource private UserRepository userRepository;

  /** 插入假数据. */
  @RequestMapping("/user/save")
  @ResponseBody
  public List<User> save() {
    List<User> userList = new ArrayList<>();
    for (int i = 0; i < 100; i++) {
      User user = new User();
      user.setUsername("admin_" + i);
      user.setPassword("pwd_" + i);
      user.setAge(i);
      user.setRole(i % 2 == 0 ? 1 : 2);
      user.setLoginDate(new Date());
      userList.add(user);
    }
    userRepository.saveAll(userList);
    return userList;
  }

  /** 用户列表. */
  @RequestMapping("/list")
  public String index2(
      @RequestParam(defaultValue = "1") Integer page,
      @RequestParam(defaultValue = "10") Integer size,
      Model model) {
    Page<User> pageBean = userRepository.findAll(PageRequest.of(page - 1, size));
    model.addAttribute("userList", pageBean.getContent());
    return "template";
  }
}
